<template>
  <div>
    <el-button type="primary" @click="dialogVisible = true">添加课程</el-button>
    <el-table :data="courses" style="width: 100%">
      <el-table-column prop="id" label="ID" width="180"></el-table-column>
      <el-table-column prop="name" label="名称" width="180"></el-table-column>
      <el-table-column prop="time" label="学分"></el-table-column>
      <el-table-column prop="point" label="学时"></el-table-column>
    </el-table>

    <el-dialog title="添加课程" v-model="dialogVisible">
      <el-form :model="newCourse" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="newCourse.name"></el-input>
        </el-form-item>
        <el-form-item label="学分">
          <el-input v-model.number="newCourse.credits"></el-input>
        </el-form-item>
        <el-form-item label="学时">
          <el-input v-model.number="newCourse.hours"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCourse">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';

export default {
  setup() {
    const courses = ref([]);
    const dialogVisible = ref(false);
    const newCourse = ref({
      name: '',
      credits: 0,
      hours: 0,
    });

    const fetchCourses = async () => {
      try {
        const response = await axios.get('http://localhost:8080/api/course');
        courses.value = response.data;
      } catch (error) {
        console.error(error);
      }
    };

    const addCourse = async () => {
      try {
        await axios.post('http://localhost:8080/api/course', newCourse.value);
        dialogVisible.value = false;
        fetchCourses();
      } catch (error) {
        console.error(error);
      }
    };

    onMounted(() => {
      fetchCourses();
    });

    return {
      courses,
      dialogVisible,
      newCourse,
      fetchCourses,
      addCourse,
    };
  },
};
</script>
